package cn.audit.repository.user;

import cn.audit.bean.pojo.User;
import cn.audit.bean.dto.UserCorrelation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @Author: 李忆枫
 * @Date: 2019/5/15 10:31
 */
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {

    /**
     * 根据用户名查询
     *
     * @param username
     * @return
     */
    @Query("select u from User u where u.username = ?1")
    User findUserByUsername(String username);

    /**
     * 关联查询
     *
     * @param department
     * @return AND (?1 = NULL  u.department = ?1)
     */
    @Query(value = "select new cn.audit.bean.dto.UserCorrelation(u,a,r) " +
            "from User u,AuditInstitution a,RoleManager r " +
            "where u.department = a.id and u.userRole = r.id " +
            "and (?1=null or u.department=?1)")
    List<UserCorrelation> findUserAll(Integer department);

    /**
     * 批量更新
     *
     * @param ids
     */
    @Modifying(clearAutomatically = true)
    @Query(value = "update User u set u.status = ?2 where u.id in ?1")
    void batchUpdate(List<Long> ids,Long status);

    /**
     * 重置密码
     *
     * @param ids
     * @param password
     */
    @Modifying(clearAutomatically = true)
    @Query(value = "update User u set u.password = ?1 where u.id in ?2")
    void batchResetPwd(String password, List<Long> ids);
}
